<?php
namespace Mouta\UserBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Mouta\AmistateBundle\utils\SfSolr;
use Mouta\AmistateBundle\Entity\Usuario;
use Mouta\AmistateBundle\utils\Strings;
use Mouta\AmistateBundle\Entity\ImagenUsuario;
use FOS\UserBundle\Controller\RegistrationController as BaseController;

class RegistrationController extends BaseController
{
    public function checkEmailAction()
    {
        $email = $this->container->get('session')->get('fos_user_send_confirmation_email/email');
        $user = $this->container->get('fos_user.user_manager')->findUserByEmail($email);
        if (null === $user) {
            return new RedirectResponse($this->container->get('router')->generate('_homepage'));
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:checkEmail.html.'.$this->getEngine(), array(
            'user' => $user,
        ));
    }
    
    public function confirmAction($token)
    {
        $user = $this->container->get('fos_user.user_manager')->findUserByConfirmationToken($token);
        if (null === $user) {
            return new RedirectResponse($this->container->get('router')->generate('_homepage'));
        }
        $user->setEnabled(true);
        $user->setLastLogin(new \DateTime());
        $this->container->get('fos_user.user_manager')->updateUser($user);
        $this->authenticateUser($user);
        return new RedirectResponse($this->container->get('router')->generate('fos_user_registration_confirmed'));
    }
    
    private function hidrateUsers($querySexo){
        $result = SfSolr::getQuery($querySexo);
        $usuarios = array();
        foreach($result['response']['docs'] as $u){
            $usuario = new Usuario();
            $usuario->setId($u['id']);
            $usuario->setNombre($u['nombre']);
            $usuario->setPara($u['para']);
            $usuario->setCumple( new \DateTime($u['cumple']));
            $usuario->setDescripcion( $u['descripcion']);
            $usuario->setPais( $u['pais']);
            $usuario->setProvincia( $u['provincia']);
            $usuario->setPuntos( $u['puntos']);
            $usuario->setVotos( $u['votos']);
            if($u['sexo'])
                $usuario->setSexo(1);
            else
                $usuario->setSexo(0);
            if($u['fotodefault']){
                $imagen = new ImagenUsuario();
                $imagen->setImagenBig($u['fotodefault']);
                $imagen->setImagen('t-'.$u['fotodefault']);
                $imagen->setDefa(1);
                $imagen->setUsuario($usuario);

                $usuario->addImagenUsuario($imagen);
            }
            $usuarios[] = $usuario;
        }
        return $usuarios;
    }
    
    public function registerAction()
    {
        $form = $this->container->get('fos_user.registration.form');
        $formHandler = $this->container->get('fos_user.registration.form.handler');
        $confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');

        $process = $formHandler->process($confirmationEnabled);
        $session = $this->container->get('Request')->getSession();
        $sexoVotado = $session->get('sexo_votado',2);
        $usuarios = array();
        if($sexoVotado == 0){
            $querySexo = '?q='.urlencode('sexo:false').'&sort='.urlencode('tienefoto desc, puntos desc') . "&start=0&rows=26";
            $usuarios = $this->hidrateUsers($querySexo);
        }elseif($sexoVotado == 1){
            $querySexo = '?q='.urlencode('sexo:true').'&sort='.urlencode('tienefoto desc, puntos desc') . "&start=0&rows=26";
            $usuarios = $this->hidrateUsers($querySexo);
        }else{
            $querySexo = '?q='.urlencode('sexo:false').'&sort='.urlencode('tienefoto desc, puntos desc') . "&start=0&rows=13";
            $usuariosTmp1 = $this->hidrateUsers($querySexo);
            $querySexo = '?q='.urlencode('sexo:true').'&sort='.urlencode('tienefoto desc, puntos desc') . "&start=0&rows=13";
            $usuariosTmp2 = $this->hidrateUsers($querySexo);
            for($i=0;$i<13;$i++){
                if(isset($usuariosTmp1[$i]))
                    $usuarios[] = $usuariosTmp1[$i];
                if(isset($usuariosTmp2[$i]))
                    $usuarios[] = $usuariosTmp2[$i];
            }
        }
        
        if ($process) {
            $user = $form->getData();

            if ($confirmationEnabled) {
                $this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
                $route = 'fos_user_registration_check_email';
            } else {
                $this->authenticateUser($user);
                $route = 'fos_user_registration_confirmed';
            }

            $this->setFlash('fos_user_success', 'registration.flash.user_created');
            $url = $this->container->get('router')->generate($route);

            return new RedirectResponse($url);
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
            'form' => $form->createView(),
            'sexoVotado' => $sexoVotado,
            'usuarios' => $usuarios,
            'theme' => $this->container->getParameter('fos_user.template.theme'),
        ));
    }
    
}